package com.example.bm.generator.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.bm.generator.pojo.Column;
import com.example.bm.generator.pojo.Table;
import com.example.bm.generator.service.IGeneratorConfigService;
import com.example.common.constant.GeneratorConstant;
import com.example.dao.mapper.GeneratorConfigMapper;
import com.example.dao.model.TGeneratorConfig;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author bryceM
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class GeneratorConfigServiceImpl extends ServiceImpl<GeneratorConfigMapper, TGeneratorConfig> implements IGeneratorConfigService {

    @Override
    public TGeneratorConfig findGeneratorConfig() {
        List<TGeneratorConfig> generatorConfigs = this.baseMapper.selectList(null);
        return CollectionUtils.isNotEmpty(generatorConfigs) ? generatorConfigs.get(0) : null;
    }

    @Override
    @Transactional
    public void updateGeneratorConfig(TGeneratorConfig generatorConfig) {
        this.saveOrUpdate(generatorConfig);
    }

    @Override
    public List<Table> getTables(Map<String, String> params, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize, true);
        String tableName = params.get("tableName");
        List<Map<String, Object>> maps = this.baseMapper.getTables(GeneratorConstant.DATABASE_NAME, tableName);
        return CollectionUtils.isEmpty(maps) ? Collections.emptyList() : maps.stream()
                .map((e) -> BeanUtil.mapToBean(e, Table.class, true))
                .collect(Collectors.toList());
    }

    @Override
    public List<Column> getColumns(String tableName) {
        List<Map<String, Object>> maps = this.baseMapper.getColumns(GeneratorConstant.DATABASE_NAME, tableName);
        return CollectionUtils.isEmpty(maps) ? Collections.emptyList() : maps.stream()
                .map((e) -> BeanUtil.mapToBean(e, Column.class, true))
                .collect(Collectors.toList());
    }
}
